package com.juyu.miliao.api.dao.redis;

import com.alibaba.fastjson.JSONObject;
import com.juyu.miliao.api.dao.mysql.SecretLanguagePlanetInfoDao;
import com.juyu.miliao.api.domain.SecretLanguagePlanetInfo;
import com.juyu.miliao.common.constant.SecretLanguagePlanetRedisKey;
import com.juyu.miliao.common.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author xuanqicheng
 * @create 2019-04-14:31
 */
@Repository
public class SecretLanguagePlanetInfoRedisDao {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private SecretLanguagePlanetInfoDao secretLanguagePlanetInfoDao;

    public List<String> getListByUserId(long userId) {
        String key = SecretLanguagePlanetRedisKey.SecretLanguagePlanetListByUserId.REDIS_KEY
                .getKeyFormat(LocalDate.now().toString(), Long.toString(userId));

        String temp = stringRedisTemplate.opsForValue().get(key);

        if (!StringUtils.isEmpty(temp)) {

            List<String> list = JSONObject.parseArray(temp, String.class);

            return list;

        } else {

            List<String> list = setSecretLanguageInfo(userId, key);
            return list;
        }

    }



    public long getSecretLanguageNumbersByTimeAndUserId(LocalDate time, long userId) {
        String key = SecretLanguagePlanetRedisKey.TheNumberOfHearingSecretLanguage
                .REDIS_KEY.getKeyFormat(time.toString(), Long.toString(userId));

        String temp = stringRedisTemplate.opsForValue().get(key);
        if (!StringUtils.isEmpty(temp)) {
            return Long.parseLong(temp);
        } else {
            return 0;
        }
    }

    /**
     * 设置听测试
     *
     * @param time
     * @param userId
     * @return
     */
    public long setSecretLanguageNumbersByTimeAndUserId(LocalDate time, long userId) {

        String key = SecretLanguagePlanetRedisKey.TheNumberOfHearingSecretLanguage
                .REDIS_KEY.getKeyFormat(time.toString(), Long.toString(userId));

        boolean bl = stringRedisTemplate.hasKey(key);

        if (bl) {

            return stringRedisTemplate.opsForValue().increment(key, 1);

        } else {

            long l = stringRedisTemplate.opsForValue().increment(key, 1);

            LocalDateTime midnight = LocalDateTime.now().plusDays(1).withHour(0)
                    .withMinute(0).withSecond(0).withNano(0);

            long exporeTime = DateUtil.getTheRemainingTimesOfTheDay(midnight, TimeUnit.MINUTES);

            stringRedisTemplate.expire(key, exporeTime, TimeUnit.MINUTES);

            return l;
        }

    }

    public void insertInfo(SecretLanguagePlanetInfo secretLanguagePlanetInfo) {

        secretLanguagePlanetInfoDao.addSecretLanguagePlanetInfo(secretLanguagePlanetInfo);

        long userId = secretLanguagePlanetInfo.getUserId();

        String key = SecretLanguagePlanetRedisKey.SecretLanguagePlanetListByUserId.REDIS_KEY
                .getKeyFormat(LocalDate.now().toString(), Long.toString(userId) );

        setSecretLanguageInfo(userId,key);
    }



    /**
     * 设置信息
     * @param userId
     * @param key
     * @return
     */
    private List<String> setSecretLanguageInfo(long userId, String key) {
        Map<String, Object> map = new HashMap<>(2);
        map.put("userId", userId);
        map.put("time", LocalDate.now().toString());
        List<String> list = secretLanguagePlanetInfoDao.selectListByTimeAndUserId(map);

        if (list.size() > 0) {
            LocalDateTime midnight = LocalDateTime.now().plusDays(1).withHour(0)
                    .withMinute(0).withSecond(0).withNano(0);

            long time = DateUtil.getTheRemainingTimesOfTheDay(midnight, TimeUnit.MINUTES);
            stringRedisTemplate.opsForValue().set(key, JSONObject.toJSONString(list), time, TimeUnit.MINUTES);

        }
        return list;
    }

    /**
     * 设置最新偷听信息
     * @param userId
     * @param questionId
     */
    public void setNewestSecretLanguageInfoByUserId(long userId,long questionId){

        String key = SecretLanguagePlanetRedisKey.SecretLanguagePlanetNewestByUserId.REDIS_KEY
                .getKeyFormat(Long.toString(userId));

        stringRedisTemplate.opsForValue().set(key,Long.toString(questionId));
    }

    public long getNewestSecretLanguageInfoByUserId(long userId) {
        String key = SecretLanguagePlanetRedisKey.SecretLanguagePlanetNewestByUserId.REDIS_KEY
                .getKeyFormat(Long.toString(userId));
        String temp = stringRedisTemplate.opsForValue().get(key);
        if(!StringUtils.isEmpty(temp)){
            return Long.parseLong(temp);
        }else{

            Map<String,Object> map = new HashMap<>(2);
            map.put("time", LocalDate.now().toString());
            map.put("userId",userId);
            List<String> list = secretLanguagePlanetInfoDao.selectListByTimeAndUserId(map);

            if(list!=null && list.size()>0){

                stringRedisTemplate.opsForValue().set(key,list.get(0));

                return Long.parseLong(list.get(0));
            }else{
                return 0;
            }

        }

    }

    /**
     * 删除听过的密语星球信息
     * @param userId
     */
    public void deleteListByUserId(long userId) {
        String time = LocalDate.now().toString();

        Map<String,Object> parameterMap = new HashMap<>(2);
        parameterMap.put("userId",userId);
        parameterMap.put("time", time);

        //删除数据库
        secretLanguagePlanetInfoDao.deleteByUserIdAndTime(parameterMap);

        String key = SecretLanguagePlanetRedisKey.SecretLanguagePlanetListByUserId.REDIS_KEY
                .getKeyFormat(time, Long.toString(userId));
        stringRedisTemplate.delete(key);

    }
}
